"use strict";
var page = require("webpage").create(),
    args = require('system').args,
    fs = require('fs'),
    siteurl = "http://jxzlxt.jhc.cn/",
    datadir = './data';

page.viewportSize = {width: 1024, height: 800};

var username, password, flow;
if(args.length != 3) {
  console.log('You must provide username, password.');
  phantom.exit();
} else {
  username = args[1];
  password = args[2];
}

var flow = [list_page, search, fill_log];

//输出浏览器的控制台输出，调试时很有帮助。
page.onConsoleMessage = function(msg) {
  console.log('CONSOLE: ' + msg);
};

page.onLoadFinished = function(status) {
  if(status !== 'success') {
    console.log('Unable to open ' + page.url);
    phantom.exit();
  }
  console.log("onLoadFinished: " + page.url);

  //如果是登录页，则直接调用login()
  if(page.url === siteurl) {
    login();
    return;
  }
//  page.render(Date.now() + '.png');
  //从flow找出下一步操作，并执行
  var next_op = flow.shift();
  console.log("next_op: " + next_op.name);
  next_op();
}

page.open(siteurl);

var content = fs.read('./data/week.json');
var records = JSON.parse(content);
if(records.length === 0) {
  console.log('No records.');
  phantom_exit();
}
var currentRecord = records.shift();

function login(){
  page.evaluate(function(uname, pass){
    $('#yhlx').val('1');
    $('#yhm').val(uname);
    $('#mm').val(pass);
    $('#btn_dl_c').click();
  }, username, password);
}

//点击填写寝室检查日志
function list_page(){
  setTimeout(function(){
    page.evaluate(function(){
      //有多项菜单名为"填写教学日志"，需特殊处理。
      var selector = '#main-nav > li:nth-child(6) > ul:nth-child(2) > li:nth-child(5) > ul:nth-child(2) > li:nth-child(1) > a:nth-child(1)';
      $(selector).click();
    });
  }, 1000);
}

function search() {
  var rd = currentRecord;
  console.log('search: ' + rd.building + ' ' + rd.room);
  setTimeout(function() {
    page.evaluate(function(rd) {
      $('#conditionReport_QS_10').val(rd.room);
      $('#conditionReport_LC_12').val(rd.building);
      $('#search_report_go_0').click();
    }, rd);
    check_exists();
  }, 2000);
}

function check_exists() {
  var count = 0;
  var interval = setInterval(function(){
    if(count > 4) {
      console.log("Tried too many times. This script will stop." );
      page.render('notfound.png');
      clearInterval(interval);
      //这里是流程的出口。
      phantom.exit();
    }
    count++;
    if(first_log_item_exists()) {
      clearInterval(interval);
      select_first_log_item();
    } else {
      console.log("Cannot find any room items. Try again.");
    }
  }, 1000);
}
//判断是页面中是否有记录
function first_log_item_exists() {
  var flag = false;
  flag = page.evaluate(function(){
    var first_check = $('#tabGrid_0 tr:nth-child(2) input[type=checkbox]');
    console.log("first_check length: " + first_check.length);
    return first_check.length == 1 ? true : false;
  });
  //  page.render('check.png');
  return flag;
}

//选择第一条寝室记录
function select_first_log_item() {
  page.evaluate(function(){
    $('#tabGrid_0 tr:nth-child(2) input[type=checkbox]').click();
    $('#btn_zxqsjc').click();
  });
}

//填写卫生检查情况
function fill_log() {
  var rd0 = currentRecord;
  console.log('fill: ' + rd0.building + ' ' + rd0.room);

  page.evaluate(function(rd){
    $('#ZC_1').val(15);
    $('#JCSJ_1_datepicker').val(rd.date);
    $('#WS_9').val(rd.problem);
    $('#ZGYQ_12').val('请对照卫生要求整改。');
    $('.form-actions button.btn:nth-child(1)').click();
  }, rd0);

  setTimeout(function() {
//    page.render('afterfill.png');
    page.evaluate(function() {
      $('.modal-footer button.btn-sm:nth-child(2)').click();
    })
    //保存records数组
    fs.write('./data/week.json', JSON.stringify(records), {mode: 'w', charset: 'utf8'});
    if(records.length > 0) {
      records = JSON.parse(fs.read('./data/week.json'));
      currentRecord = records.shift();
      flow.push(list_page, search, fill_log);
      setTimeout(function() {
        reset();
      }, 2000);
    }
  }, 1500);

}

function reset() {
  page.open('http://jxzlxt.jhc.cn/xtgl/menu_index.html');
}

function phantom_exit(){
  page.close();
  setTimeout(function(){
    phantom.exit();
  },100);
}
